package com.wangshb.upms.core.spring.security;

import com.wangshb.upms.core.common.GpResponse;
import com.wangshb.upms.core.utils.HttpUtils;
import com.wangshb.upms.core.utils.JwtTokenUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

public class JwtLogoutFilter extends GenericFilterBean {


    private RequestMatcher logoutRequestMatcher;

    public JwtLogoutFilter() {
        this.setFilterProcessesUrl("/logout");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if (requiresLogout(request, response)) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                logger.debug("Invalidating session: " + session.getId());
                session.invalidate();
            }

            JwtTokenUtils.expToken(request, new Date());

            SecurityContextHolder.getContext().setAuthentication(null);
            SecurityContextHolder.clearContext();

            HttpUtils.write(response, GpResponse.success("登出成功", null));
        }
        else {
            chain.doFilter(request, response);
        }
    }


    protected boolean requiresLogout(HttpServletRequest request,
                                     HttpServletResponse response) {
        return logoutRequestMatcher.matches(request);
    }

    public void setFilterProcessesUrl(String filterProcessesUrl) {
        this.logoutRequestMatcher = new AntPathRequestMatcher(filterProcessesUrl);
    }

}
